// Copyright Epic Games, Inc. All Rights Reserved.

#include "LyraSettingScreen.h"

#include "Input/CommonUIInputTypes.h"
#include "Player/LyraLocalPlayer.h"
#include "Settings/LyraGameSettingRegistry.h"

#include UE_INLINE_GENERATED_CPP_BY_NAME(LyraSettingScreen)

class UGameSettingRegistry;

/**
 * 初始化时调用
 * 注册UI动作绑定
 */
void ULyraSettingScreen::NativeOnInitialized()
{
	Super::NativeOnInitialized(); // 调用父类方法

	BackHandle = RegisterUIActionBinding(FBindUIActionArgs(BackInputActionData, true, FSimpleDelegate::CreateUObject(this, &ThisClass::HandleBackAction))); // 注册返回动作绑定
	ApplyHandle = RegisterUIActionBinding(FBindUIActionArgs(ApplyInputActionData, true, FSimpleDelegate::CreateUObject(this, &ThisClass::HandleApplyAction))); // 注册应用动作绑定
	CancelChangesHandle = RegisterUIActionBinding(FBindUIActionArgs(CancelChangesInputActionData, true, FSimpleDelegate::CreateUObject(this, &ThisClass::HandleCancelChangesAction))); // 注册取消更改动作绑定
}

/**
 * 创建设置注册表
 * 创建并初始化Lyra游戏设置注册表
 * @return 游戏设置注册表
 */
UGameSettingRegistry* ULyraSettingScreen::CreateRegistry()
{
	ULyraGameSettingRegistry* NewRegistry = NewObject<ULyraGameSettingRegistry>(); // 创建新的Lyra游戏设置注册表

	if (ULyraLocalPlayer* LocalPlayer = CastChecked<ULyraLocalPlayer>(GetOwningLocalPlayer())) // 如果所属本地玩家是Lyra本地玩家
	{
		NewRegistry->Initialize(LocalPlayer); // 初始化注册表
	}

	return NewRegistry; // 返回注册表
}

/**
 * 处理返回动作
 * 尝试弹出导航或应用更改并停用控件
 */
void ULyraSettingScreen::HandleBackAction()
{
	if (AttemptToPopNavigation()) // 如果尝试弹出导航成功
	{
		return;
	}

	ApplyChanges(); // 应用更改

	DeactivateWidget(); // 停用控件
}

/**
 * 处理应用动作
 * 应用更改
 */
void ULyraSettingScreen::HandleApplyAction()
{
	ApplyChanges(); // 应用更改
}

/**
 * 处理取消更改动作
 * 取消更改
 */
void ULyraSettingScreen::HandleCancelChangesAction()
{
	CancelChanges(); // 取消更改
}

/**
 * 当设置脏状态改变时的处理
 * 根据设置是否脏来添加或移除动作绑定
 * @param bSettingsDirty 设置是否脏
 */
void ULyraSettingScreen::OnSettingsDirtyStateChanged_Implementation(bool bSettingsDirty)
{
	if (bSettingsDirty) // 如果设置脏
	{
		if (!GetActionBindings().Contains(ApplyHandle)) // 如果动作绑定不包含应用句柄
		{
			AddActionBinding(ApplyHandle); // 添加应用动作绑定
		}
		if (!GetActionBindings().Contains(CancelChangesHandle)) // 如果动作绑定不包含取消更改句柄
		{
			AddActionBinding(CancelChangesHandle); // 添加取消更改动作绑定
		}
	}
	else // 如果设置不脏
	{
		RemoveActionBinding(ApplyHandle); // 移除应用动作绑定
		RemoveActionBinding(CancelChangesHandle); // 移除取消更改动作绑定
	}
}